package com.mediacloud.app.newsmodule.fragment.ugc

import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.mediacloud.app.model.adaptor.IRecyclerViewComponent
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.newsmodule.adaptor.component.ComponentHolder
import com.mediacloud.app.newsmodule.adaptor.component.ComponentManager
import com.mediacloud.app.newsmodule.adaptor.component.IEvent

class BaseComponentAdapter<T : IRecyclerViewComponent>(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var catalogItem: CatalogItem? = null
    var data: MutableList<T> = ArrayList()
    var events = ArrayList<IEvent>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val holder = ComponentManager.getComponentHolder(viewType, LayoutInflater.from(context).inflate(ComponentManager.getLayout(viewType), parent, false))
        if (holder is IEvent) {
            events.add(holder)
        }
        return holder
    }

    fun setDate(data: MutableList<T>) {
        this.data.clear()
        this.data.addAll(data)
        notifyDataSetChanged()
    }


    fun getItem(position: Int): T {
        return data[position]
    }

    override fun getItemViewType(position: Int): Int {
        return getItem(position).itemType
    }

    override fun getItemCount(): Int {
        return data.size
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {

        val holder = viewHolder as ComponentHolder
        holder.catalogItem = catalogItem
        holder.setViewHolderData(getItem(position).componentModel)



    }

    fun destroy() {
        for (event in events) {
            event.destroy()
        }
        events.clear()
    }

}